package com.dtagri.fjwlw.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.content.Intent;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import butterknife.InjectView;

import com.dtagri.fjwlw.AppContext;
import com.dtagri.fjwlw.R;
import com.dtagri.fjwlw.api.FJwlwApi;
import com.dtagri.fjwlw.base.BaseActivity;
import com.dtagri.fjwlw.base.TGson;
import com.dtagri.fjwlw.bean.ErrorMsg;
import com.dtagri.fjwlw.bean.TjAreaMsg;
import com.dtagri.fjwlw.bean.TjCompanyRegion;
import com.dtagri.fjwlw.bean.TjUsersEntity;
import com.dtagri.fjwlw.util.SimpleTextWatcher;
import com.dtagri.fjwlw.util.StringUtils;
import com.dtagri.fjwlw.util.TDevice;
import com.dtagri.fjwlw.util.TToast;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * 登录
 * 
 * @author wxjn
 * 最近修改人:CL.
 * 修改日期: 2015-11-22
 */
public class LoginActivity extends BaseActivity {

	@InjectView(R.id.et_username)
	EditText mEtUserName;

	@InjectView(R.id.et_password)
	EditText mEtPassword;

	@InjectView(R.id.iv_clear_username)
	View mIvClearUserName;

	@InjectView(R.id.iv_clear_password)
	View mIvClearPassword;

	@InjectView(R.id.btn_login)
	Button mBtnLogin;

	private final TextWatcher mUserNameWatcher = new SimpleTextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			mIvClearUserName
					.setVisibility(TextUtils.isEmpty(s) ? View.INVISIBLE
							: View.VISIBLE);
		}
	};
	private final TextWatcher mPassswordWatcher = new SimpleTextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			mIvClearPassword
					.setVisibility(TextUtils.isEmpty(s) ? View.INVISIBLE
							: View.VISIBLE);
		}
	};

	protected TjUsersEntity user;

	private final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			TToast.showToastShort("登录失败");
			hideWaitDialog();
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			hideWaitDialog();
			user = TGson.fromJson(TjUsersEntity.class, arg2);
			if (user.getId() != null) {
				// 预请求分区信息
				TjCompanyRegion tjCompanyRegion = user.getTjCompanyRegions()
						.get(AppContext.userOperate.getCurBaseIndex());
				FJwlwApi.companyEquipment(tjCompanyRegion.getRegionId(),
						mHandler2);

			} else {
				user.setUsername(mUserName);
				user.setServerIp(mServerIp);
				mEtPassword.getText().clear();
				ErrorMsg errorMsg = TGson.fromJson(ErrorMsg.class, arg2);
				AppContext.cleanLoginInfo(user);
				TToast.showToastShort(errorMsg.getMsg());
			}
		}

	};
	protected List<TjAreaMsg> tjAreaMsgs = new ArrayList<TjAreaMsg>();

	private final AsyncHttpResponseHandler mHandler2 = new AsyncHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			hideWaitDialog();

			user.setUsername(mUserName);
			mEtPassword.getText().clear();
			AppContext.cleanLoginInfo(user);
			// 分区信息获取失败也算登录失败
			TToast.showToastShort("登录失败");
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			Type type = new TypeToken<List<TjAreaMsg>>() {
			}.getType();
			tjAreaMsgs = TGson.gson.fromJson(new String(arg2), type);
			AppContext.saveAreaMsgInfo(tjAreaMsgs);
			user.setServerIp(mServerIp);
			AppContext.saveUserInfo(user);
			Intent intent = new Intent(LoginActivity.this, MainActivity.class);
			startActivity(intent);
			finish();
		}

	};

	private String mUserName;
	private String mServerIp;

	private boolean prepareForLogin() {
		if (!TDevice.hasInternet()) {
			TToast.showToastShort("当前没有可用的网络链接");
			return false;
		}
		String uName = mEtUserName.getText().toString();
		if (StringUtils.isEmpty(uName)) {
			TToast.showToastShort("请输入用户名");
			mEtUserName.requestFocus();
			return false;
		}
		// 去除邮箱正确性检测
		// if (!StringUtils.isEmail(uName)) {
		// AppContext.showToastShort(R.string.tip_illegal_email);
		// mEtUserName.requestFocus();
		// return false;
		// }
		String pwd = mEtPassword.getText().toString();
		if (StringUtils.isEmpty(pwd)) {
			TToast.showToastShort("请输入密码");
			mEtPassword.requestFocus();
			return false;
		}
		return true;
	}

	@Override
	public void onClick(View v) {

		int id = v.getId();
		switch (id) {
		case R.id.iv_clear_username:
			mEtUserName.getText().clear();
			mEtUserName.requestFocus();
			break;
		case R.id.iv_clear_password:
			mEtPassword.getText().clear();
			mEtPassword.requestFocus();
			break;
		case R.id.btn_login:
			handleLogin();
			break;
		}

	}

	private void handleLogin() {

		if (!prepareForLogin()) {
			return;
		}

		// if the data has ready
		mUserName = mEtUserName.getText().toString();
		String mPassword = mEtPassword.getText().toString();

		showWaitDialog("正在登录…");
		//用户登录成功时，服务器返回该用户所在角色的APP菜单，以及基地信息和该用户的基本信息.
		System.out.println("login-serverIp:"+AppContext.user.getServerIp());
		mServerIp = AppContext.user.getServerIp();
		FJwlwApi.login(mUserName, mPassword, mHandler);
	}

	@Override
	protected int getLayoutId() {
		return R.layout.activity_login;
	}

	@Override
	public void initView() {
		setActionBarTitle("登录");
		
		/*WindowManager windowManager = getWindowManager();    
        Display display = windowManager.getDefaultDisplay();    
        int screenWidth = screenWidth = display.getWidth();    
        int screenHeight = screenHeight = display.getHeight();  
        System.out.println("屏幕分辨率:"+screenWidth+"*"+screenHeight);*/
        
		mIvClearUserName.setOnClickListener(this);
		mIvClearPassword.setOnClickListener(this);
		mBtnLogin.setOnClickListener(this);

		mEtUserName.addTextChangedListener(mUserNameWatcher);
		mEtPassword.addTextChangedListener(mPassswordWatcher);
	}

	@Override
	public void initData() {
		mEtUserName.setText(AppContext.user.getUsername());
		mEtPassword.setText(AppContext.user.getPassword());
	}

	protected boolean hasBackButton() {
		return true;
	}
}
